import 'package:flutter/material.dart';
import 'dart:async';

late dynamic globalRefBuilderInstance = '';

class StreamCollectFactory {
  StreamController<dynamic> instance;
  List<dynamic> refs = [];
  StreamCollectFactory(this.instance);

  dispose() {
    // 清除依赖
    refs.forEach((ele) {
      ele.dispose(this);
    });
  }
}

typedef WidgetCallback = Widget Function();

class RefBuilder extends StatefulWidget {
  final WidgetCallback render;
  RefBuilder(this.render) : super();

  @override
  _RewState createState() => _RewState();
}

class _RewState extends State<RefBuilder> {
  final StreamController<dynamic> _streamController =
      StreamController<dynamic>();
  late WidgetCallback currentRender;
  late StreamCollectFactory _collectorInstance;

  @override
  void initState() {
    currentRender = widget.render;
    _collectorInstance = StreamCollectFactory(_streamController);
    super.initState();
  }

  @override
  void dispose() {
    _streamController.close();
    // 清除依赖
    _collectorInstance.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: _streamController.stream,
      builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
        globalRefBuilderInstance = _collectorInstance;
        Widget result = currentRender();
        globalRefBuilderInstance = null;
        return result;
      },
    );
  }
}
